<?php

namespace App\Http\Controllers;

use App\Models\City;
use App\Models\Fang;
use App\Models\FangAttr;
use App\Models\FangOwner;
use Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;
use OSS\Core\OssException;
use OSS\OssClient;

class FangController extends BaseController
{

    public function changFangStatus(Request $request){
        $params = $request->except('_token');
        $res = Fang::where('id',$params['fang_id'])
            ->update([
                'fang_status' => $params['fang_status']
            ]);
        if($res){
            return $this->writeJson(0, null, 'success');
        }else{
            return $this->writeJson(1000, null, 'error');
        }
    }


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $fangName = $request->get('fang_name');

        if (!empty($fangName)) {
            $hosts = [
                '127.0.0.1:9200',
            ];

            $client = ClientBuilder::create()
                ->setHosts($hosts)
                ->build();

            //检索
            $params = [
                'index' => 'fang',
                'body' => [
                    'query' => [
                        'match' => [
                            'fang_name' => $fangName
                        ]
                    ],
                    'highlight' => [
                        "pre_tags" => ["<span style='color: red'>"],
                        "post_tags" => ["</span>"],
                        "fields" => [
                            'fang_name' => new \stdClass()
                        ]

                    ]
                ]
            ];

            $results = $client->search($params);
            $data = $results['hits']['hits'];

            return view('admin.fang.index', compact('data'));
        }

        $data = Fang::all();
        return view('admin.fang.index', compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $fangOwner = FangOwner::select('id', 'name')->get();

        $fangRentTypeID = FangAttr::where('field_name', 'fang_rent_type')->value('id');
        $fangRentTypeData = FangAttr::where('pid', $fangRentTypeID)->get();

        $fangDirectionID = FangAttr::where('field_name', 'fang_direction')->value('id');
        $fangDirectionData = FangAttr::where('pid', $fangDirectionID)->get();

        $fangRentClassID = FangAttr::where('field_name', 'fang_rent_class')->value('id');
        $fangRentClassData = FangAttr::where('pid', $fangRentClassID)->get()->toArray();

        $fangConfigID = FangAttr::where('field_name', 'fang_config')->value('id');
        $fangConfigData = FangAttr::where('pid', $fangConfigID)->get()->toArray();

        $cityData = City::where('pid', 0)->get()->toArray();
        return view('admin.fang.create', compact('fangOwner', 'fangRentTypeData', 'fangDirectionData', 'fangRentClassData', 'fangConfigData', 'cityData'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $params = $request->except(['_token', 'file']);

        $geo = 'https://restapi.amap.com/v3/geocode/geo?key=7746802256f3c9e3a7b9b7e13fb6db3c&address=' . $params['fang_addr'];
        $res = file_get_contents($geo);
        $res = json_decode($res, true)['geocodes'][0]['location'];
        $res = explode(',', $res);

        $params['longitude'] = $res['0'];
        $params['latitude'] = $res['1'];


        $res = Fang::create($params);


        if ($res) {
            return redirect(route('admin.fang.index'));
        } else {
            return redirect(route('admin.fang.create'));
        }
    }


    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function UploadFile(Request $request)
    {
        $pic = $request->file('file')->store('', 'fang');
        $picPath = '/uploads/fang/' . $pic;
        return $this->writeJson(0, ['pic' => $picPath], 'success');
    }

    public function DelFile(Request $request)
    {
        $pic = $request->get('pic');
        $res = unlink(public_path() . $pic);
        if ($res) {
            return $this->writeJson(0, null, 'success');
        } else {
            //写入失败，还在当前页，来一个友好提示
            return $this->writeJson(20003, null, 'error');
        }
    }

    //房源索引
    public function createFangEs()
    {
        try {
            $hosts = [
                '127.0.0.1:9200',
            ];

            $client = ClientBuilder::create()
                ->setHosts($hosts)
                ->build();


            $params = [
                'index' => 'fang',
                'body' => [
                    'settings' => [
                        'number_of_shards' => 5,
                        'number_of_replicas' => 1
                    ],
                    'mappings' => [
                        '_source' => [
                            'enabled' => true
                        ],
                        'properties' => [
                            //对哪个字段进行搜索
                            'fang_name' => [
                                //text代表模糊搜索 keyword代表=搜索
                                'type' => 'text',
                                //中文搜索
                                'analyzer' => 'ik_max_word',
                                'search_analyzer' => 'ik_max_word'
                            ]
                        ]

                    ]
                ]
            ];

            $data = $client->indices()->create($params);
            return $this->writeJson(0, $data, 'success');
        } catch (\Exception $exception) {
            return $this->writeJson(1, $data, 'error');
        }
    }

}
